import java.util.*;

public class Bag {
	protected static StatisticalAnalyser dict;
	protected static ArrayList<Tile> tileBag;
	protected static foldocProcessor prc;
	protected static Random rgen;

	public Bag() {
		dict = new StatisticalAnalyser();
		tileBag = new ArrayList<Tile>();
		prc = new foldocProcessor();
		rgen = new Random();
		setup();

	}

	protected static boolean isEmpty() {
		return tileBag.isEmpty();
	}

	protected static void setup() {
		prc.ReadSrcDictFile();
		dict.analyze(prc.terms);
		Map<Character, Integer> dictAnalysis = dict.DistStats();
		Double totalChars = dict.totalChars();

		Set<Map.Entry<Character, Integer>> set = dictAnalysis.entrySet();
		Iterator<Map.Entry<Character, Integer>> i = set.iterator();

		while (i.hasNext()) {
			Map.Entry<Character, Integer> me = (Map.Entry<Character, Integer>) i
					.next();
			Character chr = me.getKey();
			Integer noOfChrs = me.getValue();
			Double frequency = noOfChrs * 100 / totalChars;
			Integer value = 0;
			if (frequency < 0.1)
				value = 10;
			else if (frequency < 1)
				value = 8;
			else if (frequency < 1.6)
				value = 5;
			else if (frequency < 3)
				value = 4;
			else if (frequency < 5)
				value = 3;
			else if (frequency < 8)
				value = 2;
			else
				value = 1;
			int numberOfTiles = 1 + (int) (150 * frequency / 100);
			for (int i1 = 0; i1 < numberOfTiles; i1++) {
				tileBag.add(new Tile(chr, value));
			}
		}

	}

	public String toString() {
		String bagContents = "";
		for (Tile each : tileBag) {
			bagContents += each.toString() + " , ";
		}
		return bagContents;
	}

	public static Tile getTile() {
		Tile tmp;
		if (!Bag.isEmpty())
			tmp = tileBag.remove(rgen.nextInt(tileBag.size()));
		else {
			tmp = new Tile('\t', 0);

		}
		return tmp;
	}

	public static Tile exhange(Tile t) {
		if (!Bag.isEmpty()) {
			tileBag.add(t);
			return getTile();
		} else {
			return t;
		}
	}
}
